package p4.code;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLocalStudy {

    private static final AtomicInteger nextId = new AtomicInteger(0);

    /*
     创建一个线程局部变量，将nextId存入
    */
    private static final ThreadLocal<Integer> threadId = ThreadLocal.withInitial(nextId::get);

    public static int get() {
        return threadId.get();
    }

    public static void main(String[] args) {
        for(int i=0;i<50;i++){
            new Thread(new Runnable(){
                /*
                  这里的run方法每次从线程局部变量中取值
                */
                @Override
                public void run() {
                    Integer count = get();
                    count++;
                    System.out.println(count);
                }

            }).start();
        }

    }

}
